import { signMessage } from "@wagmi/core";
import { wagmiAdapter } from './ctx/web3'
import { useAccount } from "wagmi"
import { useState, useEffect } from 'react'
import './App.css'
import snsWebSdk from '@sumsub/websdk';

function App() {
  const { address } = useAccount();
  const [accessToken, setAccessToken] = useState<string>('');
  const [, setTheme] = useState<'dark' | 'light'>('dark')

  // 主题切换功能
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme') as 'dark' | 'light' | null
    if (savedTheme) {
      setTheme(savedTheme)
      document.documentElement.setAttribute('data-theme', savedTheme)
    } else {
      // 检测系统主题偏好
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      const initialTheme = prefersDark ? 'dark' : 'light'
      setTheme(initialTheme)
      document.documentElement.setAttribute('data-theme', initialTheme)
    }
  }, [])

  // const toggleTheme = () => {
  //   const newTheme = theme === 'dark' ? 'light' : 'dark'
  //   setTheme(newTheme)
  //   document.documentElement.setAttribute('data-theme', newTheme)
  //   localStorage.setItem('theme', newTheme)
  // }
  const generateRandomFromSeed = (address: string, timestamp: number) => {
    // 将地址转换为数字种子
    let seed = 0
    for (let i = 0; i < address.length; i++) {
      seed += address.charCodeAt(i)
    }

    // 结合时间戳
    seed = (seed + timestamp) % 2147483647

    // 使用线性同余生成器生成随机数
    const a = 1664525
    const c = 1013904223
    const m = Math.pow(2, 32)

    seed = (a * seed + c) % m

    // 返回0-1之间的随机数
    return seed / m
  }

  const handleLogin = async () => {
    if (!address) return
    alert(address)
    try {
      const timestamp = Date.now()
      const randomNumber = generateRandomFromSeed(address || '', timestamp)
      
      // 使用包含地址和时间戳的消息格式，这是更安全的做法
      const _message = `Welcome to RWA Platform! Please sign this message to authenticate.`
      
      console.log('开始签名...')
      console.log('消息:', _message)
      console.log('钱包地址:', address)
      console.log('wagmi配置:', wagmiAdapter.wagmiConfig)
      
      // 尝试签名
      let signature: string
      try {
        signature = await signMessage(wagmiAdapter.wagmiConfig, {
          account: address,
          message: _message
        })
      } catch (signError) {
        console.error('签名失败:', signError)
        throw new Error(`签名失败: ${signError instanceof Error ? signError.message : '未知错误'}`)
      }
      
      console.log('签名成功:', signature)
      console.log('签名长度:', signature.length)
      console.log('签名类型:', typeof signature)
      
      // 更详细的签名格式验证
      const isValidFormat = /^0x[a-fA-F0-9]+$/.test(signature)
      const hasCorrectLength = signature.length === 132 // 0x + 130个字符
      const isPersonalSign = signature.length === 132
      
      console.log('签名格式验证:')
      console.log('- 基本格式正确:', isValidFormat)
      console.log('- 长度正确(132字符):', hasCorrectLength)
      console.log('- 可能是personal_sign:', isPersonalSign)
      console.log('- 完整签名:', signature)
      
      if (!isValidFormat) {
        console.error('❌ 签名格式完全错误，不是有效的十六进制字符串')
      } else if (!hasCorrectLength) {
        console.warn('⚠️ 签名长度异常，期望132字符，实际:', signature.length)
        console.log('可能的签名类型:')
        console.log('- personal_sign: 132字符 (0x + 130)')
        console.log('- typedData: 132字符 (0x + 130)')
        console.log('- 其他格式: 长度可能不同')
      } else {
        console.log('✅ 签名格式看起来正确')
      }
      
      console.log('生成的随机数:', randomNumber)
      
      const response = await window.fetch('http://127.0.0.1:3000/api/v1/auth/wallet-login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          walletAddress: address,
          message: _message,
          signature: signature,
          fullName: randomNumber
        })
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const data = await response.json()
      console.log('login response data:', data)
      setAccessToken(data.accessToken);
      // launchWebSdk(data.accessToken);
      
    } catch (error) {
      console.error('登录过程中发生错误:', error)
      alert(`登录失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }


  const getNewAccessToken = () => {
    return Promise.resolve('newAccessToken'); // get a new token from your backend
  }


  /**
 * @param accessToken - access token that you generated on the backend
 */
  const launchWebSdk = (accessToken: string) => {
    let snsWebSdkInstance = snsWebSdk
      .init(
        accessToken,
        // token update callback, must return Promise
        // Access token expired
        // get a new one and pass it to the callback to re-initiate the WebSDK
        () => getNewAccessToken()
      )
      .withConf({
        lang: "en", //language of WebSDK texts and comments (ISO 639-1 format)
        theme: "dark" as "dark" | "light",
      })
      .withOptions({ addViewportTag: false, adaptIframeHeight: true })
      // see below what kind of messages WebSDK generates
      .on("idCheck.onStepCompleted", (payload) => {
        console.log("onStepCompleted", payload);
      })
      .on("idCheck.onError", (error) => {
        console.log("onError", error);
      })
      .build();
    // you are ready to go:
    // just launch the WebSDK by providing the container element for it
    snsWebSdkInstance.launch("#sumsub-websdk-container");
  }

  const handleKYC = () => {
    window.fetch('http://127.0.0.1:3000/api/v1/kyc/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${accessToken}`
      },
      body: JSON.stringify({
        walletAddress: address
      })
    }).then(res => res.json())
      .then(data => {
        setAccessToken(data.accessToken);
        // 认证
        launchWebSdk(data.accessToken);
      })
  }

  return (
    <>
      {/* 主题切换按钮 */}
      {/* <div className="fixed top-4 right-4 z-50">
        <button
          onClick={toggleTheme}
          className="theme-toggle-btn"
          aria-label={`切换到${theme === 'dark' ? '浅色' : '深色'}主题`}
        >
          {theme === 'dark' ? '☀️' : '🌙'}
        </button>
      </div> */}
      <div className="h-screen w-screen">
        <div className="flex flex-col items-center justify-center">
          <button className="mt-3 text-white bg-blue-500! p-2 rounded-md" onClick={handleLogin}>1:登陆</button>
          <button className="mt-3 text-white bg-blue-500! p-2 rounded-md" onClick={handleKYC} disabled={!accessToken}>2:认证</button>
        </div>
        <appkit-button />
      </div>
      <div id="sumsub-websdk-container"></div>
    </>
  )
}

export default App
